import React, {useRef, useState} from "react";
import {NavBar, Pagination, SearchBar, WhiteSpace, WingBlank, Toast, Icon} from "antd-mobile";
import {useHistory} from 'react-router-dom';

import {ContentList} from "../../component/cardContent";
import CopyFooter from "../../component/copyFooter";
import {search} from "../../requests";


export default function Home(props) {
    let rHistory = useHistory();

    let [currentPage, setCurrentPage] = useState(0);
    let [total, setTotal] = useState(0);
    let [data, setData] = useState([]);

    let nowKey = useRef("");

    return (
        <div>
            <NavBar mode="dark" rightContent={<Icon type={"ellipsis"}
                                                    onClick={() => rHistory.push("/boxlist")}/>}>储物码</NavBar>
            <SearchBar placeholder={"搜索物品"} onSubmit={(val) => {
                if (!val) {
                    Toast.fail("内容不能为空", 3, null, true);
                    return;
                }
                nowKey.current = val;
                search({
                    query: nowKey.current,
                    page: currentPage
                }).then(resp => {
                    setData(resp.data.result);
                    setTotal(resp.data.total);
                    setCurrentPage(resp.data.current);
                });
            }}/>

            <WhiteSpace/>

            <ContentList data={data}/>

            <WhiteSpace/>
            <WingBlank>
                {data.length > 0 ? (
                    <Pagination total={total} current={currentPage} onChange={(current => {
                        search({
                            query: nowKey.current,
                            page: current
                        }).then(resp => {
                            setData(resp.data.result);
                            setTotal(resp.data.total);
                            setCurrentPage(resp.data.current);
                        });
                    })}/>
                ) : ""}
            </WingBlank>

            <CopyFooter/>
        </div>
    );
}